package com.vietnam.power.dao.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vietnam.power.dao.UserDao;
import com.vietnam.power.domain.UserSearchCriteria;
import com.vietnam.power.persitence.UserInfo;

@Repository
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public class UserDaoImpl extends GenericDaoImpl implements UserDao {

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public UserInfo getUserByUserName(String username) {
		UserInfo user = new UserInfo();
		Criteria cr = getSessionFactory().getCurrentSession().createCriteria(UserInfo.class);
		// Add restriction.
		cr.add(Restrictions.eq("userName", username));
		List<UserInfo> list = cr.list();
		if (CollectionUtils.isNotEmpty(list)) {
			user = list.get(0);
		}

		return user;
	}

	public void updateUserInfo(UserInfo userInfo) {
		merge(userInfo);
	}

	public void createUserInfo(UserInfo userInfo) {
		save(userInfo);
	}

	public UserInfo getUserById(int id) {
		return findById(UserInfo.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<UserInfo> searchUser(UserSearchCriteria criteria) {
		Criteria cr = getSessionFactory().getCurrentSession().createCriteria(UserInfo.class);
		// Add restriction.
		if (StringUtils.isNotBlank(criteria.getUserName()))
			cr.add(Restrictions.ilike("userName", criteria.getUserName(), MatchMode.ANYWHERE));

		if (StringUtils.isNotBlank(criteria.getEmail()))
			cr.add(Restrictions.eq("email", criteria.getEmail()));

		if (criteria.getCurrentUserId() != null)
			cr.add(Restrictions.ne("id", criteria.getCurrentUserId()));

		cr.add(Restrictions.ne("userName", "sysadmin"));

		return cr.list();
	}

}
